package com.ganinfo.common.token;

import java.util.UUID;

import com.ganinfo.common.constant.PropertiesConstant;
import com.ganinfo.common.redis.RedisUtils;
/**
 * @ClassName:   RidesToken
 * @Description: TODO
 * @author:      sks
 * @date:        2017年2月28日 下午4:30:10
 */
public class RidesToken implements IToken{
	
	//private Jedis j = null;
	
	public String login(String userid) {
		
		String returncode = "";
		//判断是否已经登录，若是，重新设定过期时间,返回原有的uuid
		try {
			String tk = RedisUtils.get(userid);
			int redisExpire = Integer.parseInt(PropertiesConstant.CONFIG_PRO.getStr("redisExpire"));
			
			if(tk!=null){
				RedisUtils.expire(userid,redisExpire);
				RedisUtils.expire(tk, redisExpire);
				returncode = tk;
			}else{
				//不在登录状态，将信息写入redis,并返回新生成的uuid
				String uuid = getUUID();
				RedisUtils.set(userid,uuid,redisExpire);
				RedisUtils.set(uuid,userid,redisExpire);
				returncode = uuid;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returncode;
		
		
	}

	
	public String getUUID() {
		String uuid = UUID.randomUUID().toString().replace("-", "");
		return uuid;
	}
	
	@Override
	public void logout(String userid) {
		try {
			String tk = RedisUtils.get(userid);
			if(tk!=null){
				RedisUtils.del(tk);
				RedisUtils.del(userid);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public String getUserid(String token){
		String usercode = null;
		if(token!=null){
			try {
				usercode =RedisUtils.get(token);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return usercode;
	}
	
	@Override
	public boolean validate(String token) {
		Boolean returncode = false;
		//判断传过来的token是否为空
		if(token!=null){
			try {
				String tk =RedisUtils.get(token);
				//已经登录的
				if(tk!=null){
					//存活时间重新计数
					RedisUtils.expire(token,30*24*60*60);
					RedisUtils.expire(tk, 30*24*60*60);
					returncode = true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return returncode;
		
	}
	
}
